<template>
  <div class="completion-container">
    <div class="tit01">审计项目完成情况</div>
    <div class="content-wrapper">
      <!-- 左侧：项目状态饼图 -->
      <div class="status-chart">
        <div class="chart-container" ref="chartContainer"></div>
      </div>
      
      <!-- 右侧：项目进度列表 -->
      <div class="progress-list">
        <div class="progress-header-row">
          <div class="progress-title">进行中项目进度</div>
          <button class="detail-btn" @click="showDetailList">详细</button>
        </div>
        
        <!-- 完成度统计 -->
        <div class="progress-stats">
          <div class="stat-item stat-high">
            <div class="stat-label">80%以上</div>
            <div class="stat-value">{{ progressStats.high }}个</div>
          </div>
          <div class="stat-item stat-medium">
            <div class="stat-label">50%-80%</div>
            <div class="stat-value">{{ progressStats.medium }}个</div>
          </div>
          <div class="stat-item stat-low">
            <div class="stat-label">50%以下</div>
            <div class="stat-value">{{ progressStats.low }}个</div>
          </div>
        </div>
        
        <div class="progress-scroll" ref="progressScroll">
          <div class="progress-items" :style="{ transform: `translateY(-${scrollOffset}px)` }">
            <div 
              v-for="(project, index) in projectList" 
              :key="index"
              class="progress-item"
            >
              <div class="project-header">
                <div class="project-name" :title="project.name">{{ project.name }}</div>
                <div class="project-stage">{{ project.linkName }}</div>
              </div>
              <div class="progress-bar-container">
                <div class="progress-bar">
                  <div 
                    class="progress-fill" 
                    :style="{ width: `${project.value}%` }"
                  ></div>
                </div>
                <div class="progress-value">{{ project.value.toFixed(1) }}%</div>
              </div>
              <div class="project-team">
                <span v-if="project.leaderName" class="team-role">组长: {{ project.leaderName }}</span>
                <span v-if="project.busRefereeName" class="team-role">主审: {{ project.busRefereeName }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import * as echarts from 'echarts'
import { queuedFetch } from '../utils/queuedRequest.js'

const emit = defineEmits(['showDetail'])

const chartContainer = ref(null)
const progressScroll = ref(null)
let chartInstance = null
let scrollTimer = null

const apiUrl = '/coolv/edatasource/jdbcmgr.do'
const projectList = ref([])
const scrollOffset = ref(0)

// 计算不同完成度区间的项目数量
const progressStats = computed(() => {
  const stats = {
    high: 0,    // 80%以上
    medium: 0,  // 50%-80%
    low: 0      // 50%以下
  }
  
  projectList.value.forEach(project => {
    const progress = project.value
    if (progress >= 80) {
      stats.high++
    } else if (progress >= 50) {
      stats.medium++
    } else {
      stats.low++
    }
  })
  
  return stats
})

// 获取项目状态分布数据
const fetchStatusDistribution = async () => {
  const sql = `
    SELECT
      t1.PLAN_YEAR,
      COALESCE(NULLIF(TRIM(t2.DISPLAY_VALUE), ''), '未立项') AS STATUS,
      COUNT(*) AS NUM
    FROM V_PLAN_PRJ t1
    LEFT JOIN (
      SELECT DICT_KEY, REAL_VALUE, DISPLAY_VALUE FROM PUB_DICT_DEF WHERE DICT_KEY = 'SAP_XMZT' AND REAL_VALUE <> '#'
    ) t2 ON t1.PRJ_STATUS = t2.REAL_VALUE
    WHERE t1.PLAN_TYPE = '1'
      AND t1.PLAN_YEAR = (SELECT MAX(PLAN_YEAR) FROM V_PLAN_PRJ)
    GROUP BY
      t1.PLAN_YEAR,
      COALESCE(NULLIF(TRIM(t2.DISPLAY_VALUE), ''), '未立项'),
      t2.REAL_VALUE
    ORDER BY STATUS
  `

  // SQL编码：与 amsedb 数据源保持一致
  // 1. URL编码
  let encodedSql = encodeURIComponent(sql)
  // 2. Base64编码
  encodedSql = btoa(encodedSql)

  const formBody = new URLSearchParams()
  formBody.set('action', 'exesql')
  formBody.set('jdbcName', 'DB2')
  formBody.set('enc', 'true')
  formBody.set('sql', encodedSql)
  formBody.set('pageIndex', 'undefined')
  formBody.set('pageSize', '100')
  formBody.set('isSys', 'false')

  console.debug('[CompletionRate] 请求年度状态分布 SQL:', sql)

  // 使用队列化请求
  const res = await queuedFetch(apiUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
    body: formBody.toString()
  }, {
    name: '项目状态分布',
    priority: 5  // 高优先级
  })
  const data = await res.json()

  if (data && Array.isArray(data.datas) && data.datas.length > 0) {
    const items = data.datas.map(row => ({
      year: row[0],
      status: row[1] || '未立项',
      value: Number(row[2]) || 0
    }))
    const year = items[0]?.year || ''
    const result = {
      year,
      items: items.map(item => ({ name: item.status, value: item.value }))
    }
    console.debug('[CompletionRate] DB 返回状态分布:', result)
    return result
  }

  console.warn('[CompletionRate] 未获取到年度状态数据，使用兜底数据')
  return { year: '', items: [] }
}

// 获取项目进度数据
const fetchProjectProgress = async () => {
  const sql = `
SELECT t1.PRJ_YEAR prjYear,t1.PROJECT_NAME name,
t1.PROGRESS value,
nvl(t4.USER_TYPE_LEADER,'') leaderName,
nvl(t4.USER_TYPE_REFEREE,'') dpleaderName,
nvl(t4.USER_TYPE_BUS_REFEREE,'') busRefereeName,
nvl(t4.USER_TYPE_DATA_REFEREE,'') dataRefereeName,
nvl(t4.USER_TYPE_MEMBER,'') member,
t2.DISPLAY_VALUE linkName 
FROM (
	SELECT t3.PLAN_YEAR PRJ_YEAR,t1.PRJ_STAGE,t1.PROJECT_NAME,t1.PRJ_STATUS,
	t1.PROC_ID,t1.PRJ_CODE,nvl(t2.PROGRESS,0) PROGRESS
	FROM SAP_PLAN_INFO t3
	LEFT JOIN SAP_PRJ_INFO t1
	ON t3.PLAN_CODE = t1.PLAN_CODE
	LEFT JOIN (
		SELECT t1.PRJ_CODE,
		sum(CAST(nvl(t3.PROC_PERCENT,0) AS DECIMAL(18,2))) PROGRESS
		FROM (
			SELECT t1.PROJECT_NAME,t1.PROC_ID,t1.PRJ_CODE,nvl(t2.LOCK_STATUS,1) LOCK_STATUS,nvl(t2.LINK_ID,0) LINK_ID
			FROM SAP_PRJ_INFO t1
			LEFT JOIN SAP_PRJ_LINK_DTL t2
			ON t1.PRJ_CODE = t2.PRJ_CODE
		) t1
		LEFT JOIN SAP_PROC_LINK_REL t3
		ON t1.PROC_ID = t3.PROC_ID AND t1.LINK_ID = t3.LINK_ID
		WHERE t1.LOCK_STATUS = '2'
		GROUP BY t1.PRJ_CODE
	) t2
	ON t3.PRJ_CODE = t2.PRJ_CODE
	WHERE t3.PLAN_TYPE = '1'
	AND t3.PLAN_STATUS = '3'
	AND t1.PRJ_CODE IS NOT NULL 
) t1
LEFT JOIN PUB_DICT_DEF t2
ON t1.PRJ_STAGE = t2.REAL_VALUE AND t2.dict_key = 'SAP_XMJD'
LEFT JOIN (
	SELECT t1.PRJ_CODE,
	listagg(CASE WHEN t1.USER_TYPE = '1' THEN t3.STAFF_NAME END ,'、') USER_TYPE_LEADER,
	listagg(CASE WHEN t1.USER_TYPE = '2' THEN t3.STAFF_NAME END ,'、') USER_TYPE_REFEREE,
	listagg(CASE WHEN t1.USER_TYPE = '3' THEN t3.STAFF_NAME END ,'、') USER_TYPE_BUS_REFEREE,
	listagg(CASE WHEN t1.USER_TYPE = '4' THEN t3.STAFF_NAME END ,'、') USER_TYPE_DATA_REFEREE,
	listagg(CASE WHEN t1.USER_TYPE = '5' THEN t3.STAFF_NAME END ,'、') USER_TYPE_MEMBER
	FROM SAP_PRJ_USER_DTL t1
	LEFT JOIN PUB_USER_INFO t2 
	ON t1.USER_ID = t2.USER_ID 
	LEFT JOIN PUB_STAFF_INFO t3 
	ON t2.STAFF_ID = t3.STAFF_ID 
	GROUP BY t1.PRJ_CODE
) t4
ON t1.PRJ_CODE = t4.PRJ_CODE
WHERE t1.PRJ_STATUS = '3'
GROUP BY t1.PRJ_YEAR,t1.PROGRESS,t1.PROJECT_NAME,t4.USER_TYPE_LEADER,t4.USER_TYPE_REFEREE,t4.USER_TYPE_BUS_REFEREE,t4.USER_TYPE_DATA_REFEREE,t4.USER_TYPE_MEMBER,t2.DISPLAY_VALUE
UNION ALL 
SELECT t.PRJ_YEAR,t.NAME,sum(CAST(t.weight AS DECIMAL(18,2))),
nvl(t1.USER_TYPE_LEADER,'') leaderName,
nvl(t1.USER_TYPE_REFEREE,'') dpleaderName,
nvl(t1.USER_TYPE_BUS_REFEREE,'') busRefereeName,
'',
nvl(t1.USER_TYPE_MEMBER,'') member,
t.MODULES_NAME 
FROM (
	SELECT CAST(t6.YAER AS varchar(4)) PRJ_YEAR,t1.ID,t1.NAME,t4.MODULES_NAME,
	CAST(SUBSTR(t3.CFG,posstr(t3.CFG,'weight')+8,posstr(t3.CFG,'}')-posstr(t3.CFG,'weight')-8) AS varchar(10)) weight
	FROM T_AMIS_PLAN t6
	LEFT JOIN T_AMIS_PRJ t1
	ON t6.ID = t1.PLAN_ID
	LEFT JOIN T_AMIS_PRJTYPE t2
	ON t1.PRJ_TYPE = t2.ID 
	LEFT JOIN T_AMIS_PRJTYPE_M t3
	ON t2.ID = t3.ID 
	LEFT JOIN AUD_CHARTS_PROJECT_STAGE t4
	ON t1.MODULE = t4.modules_id
	LEFT JOIN AUD_CHARTS_PROJECT_STAGE t5
	ON t3.MODULE = t5.modules_id
	WHERE t6.YEARPLAN = '1'
	AND t6.STATUS = '3'
	AND t1.STATUS in ('3', '4', '7', '10')
	AND posstr(t3.CFG,'weight') != 0
	AND t5.ID BETWEEN 0 AND t4.ID-1
	ORDER BY t1.NAME,t4.ID,t5.ID
) t
LEFT JOIN (
		SELECT t1.PRJ_ID,
		listagg(CASE WHEN t1.ROLE_ID = '1' THEN t2.NAME END,'、') USER_TYPE_LEADER,
		listagg(CASE WHEN t1.ROLE_ID = 'GVM' THEN t2.NAME END,'、') USER_TYPE_REFEREE,
		listagg(CASE WHEN t1.ROLE_ID = '2' THEN t2.NAME END,'、') USER_TYPE_BUS_REFEREE,
		listagg(CASE WHEN t1.ROLE_ID = 'GM' THEN t2.NAME END,'、') USER_TYPE_MEMBER
		FROM T_AMIS_PRJ_MEMBER t1
		LEFT JOIN T_SYS_USER t2
		ON t1.USER_ID = t2.ID
		GROUP BY t1.PRJ_ID
) t1
ON t.ID = t1.PRJ_ID
GROUP BY t.NAME,t.PRJ_YEAR,t1.USER_TYPE_LEADER,t1.USER_TYPE_REFEREE,t1.USER_TYPE_BUS_REFEREE,t1.USER_TYPE_MEMBER,t.MODULES_NAME
ORDER BY value DESC
  `

  // SQL编码：与 amsedb 数据源保持一致
  // 1. URL编码
  let encodedSql = encodeURIComponent(sql)
  // 2. Base64编码
  encodedSql = btoa(encodedSql)

  const formBody = new URLSearchParams()
  formBody.set('action', 'exesql')
  formBody.set('jdbcName', 'DB2')
  formBody.set('enc', 'true')
  formBody.set('sql', encodedSql)
  formBody.set('pageIndex', 'undefined')
  formBody.set('pageSize', '100')
  formBody.set('isSys', 'false')

  console.debug('[CompletionRate] 请求项目进度 SQL')

  try {
    // 使用队列化请求
    const res = await queuedFetch(apiUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
      body: formBody.toString()
    }, {
      name: '项目进度数据',
      priority: 4
    })
    const data = await res.json()

    if (data && Array.isArray(data.datas) && data.datas.length > 0) {
      const projects = data.datas.map(row => ({
        prjYear: row[0] || '',
        name: row[1] || '',
        value: Number(row[2]) || 0,
        leaderName: row[3] || '',
        dpleaderName: row[4] || '',
        busRefereeName: row[5] || '',
        dataRefereeName: row[6] || '',
        member: row[7] || '',
        linkName: row[8] || ''
      }))
      console.debug('[CompletionRate] DB 返回项目进度数据:', projects)
      return projects
    }

    console.warn('[CompletionRate] 未获取到项目进度数据，使用兜底数据')
    return []
  } catch (error) {
    console.error('[CompletionRate] 获取项目进度失败:', error)
    return []
  }
}

// 初始化饼图
const initChart = async () => {
  if (!chartContainer.value) return
  
  chartInstance = echarts.init(chartContainer.value)

  const statusDistribution = await fetchStatusDistribution().catch((err) => {
    console.error('[CompletionRate] 获取状态分布失败:', err)
    return { year: '', items: [] }
  })

  const fallbackStatus = {
    year: new Date().getFullYear().toString(),
    items: [
      { name: '作业中', value: 28 },
      { name: '未立项', value: 9 },
      { name: '已归档', value: 33 },
      { name: '终止', value: 1 }
    ]
  }

  const pieData = statusDistribution.items.length ? statusDistribution.items : fallbackStatus.items
  const pieYear = statusDistribution.year || fallbackStatus.year
  console.debug('[CompletionRate] 最终饼图数据:', pieYear, pieData)

  const option = {
    color: ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4'],
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#29D9D5',
      borderWidth: 1,
      textStyle: { color: '#fff', fontSize: 13, fontWeight: 'normal' },
      padding: [10, 15],
      extraCssText: 'box-shadow: 0 0 20px rgba(41, 217, 213, 0.5); border-radius: 8px;',
      confine: true,
      formatter: params => {
        const total = pieData.reduce((sum, item) => sum + item.value, 0)
        const percent = total ? ((params.value / total) * 100).toFixed(1) : 0
        return `<div style="color:#fff;">
          <div style="font-weight:bold;margin-bottom:5px;color:#29D9D5;">${params.name}</div>
          <div>数量：${params.value} 个</div>
          <div>占比：${percent}%</div>
        </div>`
      }
    },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: '10%',
      itemGap: 12,
      itemWidth: 18,
      itemHeight: 12,
      textStyle: { 
        color: '#fff', 
        fontSize: 12,
        rich: {
          name: {
            fontSize: 12,
            color: '#fff',
            padding: [0, 8, 0, 5]
          },
          value: {
            color: '#29D9D5',
            fontSize: 12,
            fontWeight: 'bold'
          }
        }
      },
      backgroundColor: 'rgba(0, 20, 40, 0.3)',
      borderRadius: 6,
      padding: [10, 15, 10, 10],
      formatter: name => {
        const match = pieData.find(item => item.name === name)
        if (match) {
          return `{name|${name}}{value|${match.value}个}`
        }
        return name
      }
    },
    series: [
      {
        name: `${pieYear}年项目状态`,
        type: 'pie',
        radius: '75%',
        center: ['27%', '52%'],  // 往左移动，避免与图例重叠
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 0,
          borderColor: 'transparent',
          borderWidth: 0,
          shadowBlur: 8,
          shadowColor: 'rgba(0, 0, 0, 0.2)'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 15,
            shadowOffsetX: 0,
            shadowColor: 'rgba(41, 217, 213, 0.4)',
            borderWidth: 0,
            borderColor: 'transparent'
          },
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          },
          scale: true,
          scaleSize: 10
        },
        label: {
          show: true,
          position: 'inside',
          color: '#fff',
          fontSize: 14,
          fontWeight: 'bold',
          formatter: '{b}\n{d}%'
        },
        labelLine: {
          show: false
        },
        data: pieData
      }
    ]
  }

  chartInstance.setOption(option)
}

// 初始化项目进度列表
const initProjectList = async () => {
  const projects = await fetchProjectProgress()
  
  if (projects.length === 0) {
    // 兜底数据
    projectList.value = [
      {
        prjYear: '2025',
        name: '关于2024年度贺州八步东盈村镇银行股份有限公司全面审计',
        value: 0,
        leaderName: '翟彩虹',
        busRefereeName: '冯俊玲',
        linkName: '审计准备'
      },
      {
        prjYear: '2025',
        name: '关于2024年度消费者权益保护专项审计',
        value: 0,
        leaderName: '李国深',
        busRefereeName: '刘旭妮',
        linkName: '审计准备'
      },
      {
        prjYear: '2025',
        name: '关于2024年度薪酬管理专项审计',
        value: 7,
        leaderName: '李国深',
        busRefereeName: '吴君仪',
        linkName: '审计准备'
      },
      {
        prjYear: '2025',
        name: '关于2024年度财务管理专项审计',
        value: 7,
        leaderName: '李国深',
        busRefereeName: '张振文',
        linkName: '审计准备'
      }
    ]
  } else {
    projectList.value = projects
  }
  
  // 启动滚动
  startScroll()
}

// 显示详细列表
const showDetailList = () => {
  emit('showDetail', projectList.value)
}

// 滚动动画
const startScroll = () => {
  if (projectList.value.length <= 3) return // 如果项目少于等于3个，不需要滚动
  
  scrollTimer = setInterval(() => {
    scrollOffset.value += 1
    
    // 计算滚动区域高度
    const itemHeight = 90 // 每个项目项的大概高度
    const totalHeight = projectList.value.length * itemHeight
    const visibleHeight = 200 // 可见区域高度
    
    // 当滚动到底部时，重置到顶部
    if (scrollOffset.value >= totalHeight - visibleHeight + itemHeight) {
      scrollOffset.value = 0
    }
  }, 50) // 每50ms滚动1px
}

onMounted(() => {
  initChart()
  initProjectList()
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  if (scrollTimer) {
    clearInterval(scrollTimer)
  }
})
</script>

<style scoped>
.completion-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.tit01 {
  flex-shrink: 0;
}

.content-wrapper {
  flex: 1;
  display: flex;
  gap: 15px;
  padding: 10px;
  overflow: hidden;
}

.status-chart {
  flex: 0 0 35%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-container {
  width: 100%;
  height: 100%;
  min-height: 160px;
}

.progress-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.progress-header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.progress-title {
  font-size: 13px;
  color: #29D9D5;
  font-weight: bold;
  padding-left: 10px;
  border-left: 3px solid #29D9D5;
}

.detail-btn {
  background: linear-gradient(135deg, #29D9D5 0%, #4ECDC4 100%);
  color: #fff;
  border: none;
  padding: 6px 16px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(41, 217, 213, 0.3);
}

.detail-btn:hover {
  background: linear-gradient(135deg, #4ECDC4 0%, #29D9D5 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(41, 217, 213, 0.5);
}

.detail-btn:active {
  transform: translateY(0);
}

.progress-stats {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  padding: 0 5px;
}

.stat-item {
  flex: 1;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  padding: 8px 10px;
  text-align: center;
  border-left: 3px solid;
  transition: all 0.3s ease;
}

.stat-item:hover {
  background: rgba(255, 255, 255, 0.08);
  transform: translateY(-2px);
}

.stat-high {
  border-left-color: #91CC75;
}

.stat-medium {
  border-left-color: #FAC858;
}

.stat-low {
  border-left-color: #EE6666;
}

.stat-label {
  font-size: 10px;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 4px;
}

.stat-value {
  font-size: 16px;
  font-weight: bold;
  color: #fff;
}

.stat-high .stat-value {
  color: #91CC75;
}

.stat-medium .stat-value {
  color: #FAC858;
}

.stat-low .stat-value {
  color: #EE6666;
}

.progress-scroll {
  flex: 1;
  overflow: hidden;
  position: relative;
  mask-image: linear-gradient(to bottom, transparent 0%, black 10%, black 90%, transparent 100%);
  -webkit-mask-image: linear-gradient(to bottom, transparent 0%, black 10%, black 90%, transparent 100%);
}

.progress-items {
  transition: transform 0.05s linear;
}

.progress-item {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  padding: 10px 12px;
  margin-bottom: 10px;
  border-left: 3px solid #29D9D5;
}

.project-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
  gap: 10px;
}

.project-name {
  flex: 1;
  color: #fff;
  font-size: 12px;
  font-weight: 500;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.project-stage {
  flex-shrink: 0;
  background: rgba(41, 217, 213, 0.2);
  color: #29D9D5;
  font-size: 10px;
  padding: 2px 8px;
  border-radius: 10px;
  border: 1px solid rgba(41, 217, 213, 0.4);
}

.progress-bar-container {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 6px;
}

.progress-bar {
  flex: 1;
  height: 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #29D9D5 0%, #4ECDC4 100%);
  border-radius: 4px;
  transition: width 0.3s ease;
  box-shadow: 0 0 8px rgba(41, 217, 213, 0.5);
}

.progress-value {
  flex-shrink: 0;
  color: #29D9D5;
  font-size: 12px;
  font-weight: bold;
  min-width: 45px;
  text-align: right;
}

.project-team {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.team-role {
  color: rgba(255, 255, 255, 0.7);
  font-size: 10px;
}
</style>